package com.example.hi;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;



import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Documented;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity  implements Runnable {

   private float dollarRate;
   private float euroRate;
    private float wonRate;
    private final String TAG="Rate";
    Handler  handle;
    EditText rmb;
    TextView show;
    private final static long ONE_DAY_MSECOND = 24 * 60 * 60 * 1000;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent i = new Intent();
        //创建闹钟对象
        AlarmManager aManager = (AlarmManager)getSystemService(Service.ALARM_SERVICE);
        PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        // 设置闹钟为可将手机从休眠中唤醒，第一次开始时间为现在，间隔为一天，完成的任务为pendingIntent
        aManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ONE_DAY_MSECOND, pi);


//        loadFromSP();
        //获取文件中保存的数据
        handle = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                Log.i(TAG, "handleMessage:收到消息");
                if ((msg.what == 6)) {
                    String str = (String) msg.obj;
                    Log.i(TAG, "handleMassage : str=" + str);
                    show.setText(show.getText().toString()+str);
                    Toast.makeText(MainActivity.this,"汇率已更新", Toast.LENGTH_SHORT).show();

                }
                super.handleMessage(msg);
            }
        };

    Thread thread =new Thread((this));
    thread.start();



        rmb  = (EditText) findViewById(R.id.rmb);
        show = (TextView) findViewById(R.id.show);}



    public void onClick(View btn){
        Log.i(TAG,"onClick:");
        String str = rmb.getText().toString();
        Log.i(TAG,"onClick: get str+" +str);

        float r=0;
        if(str.length()>0){
            r = Float.parseFloat(str);
        }else{
            Toast.makeText(this,"请输入内容",Toast.LENGTH_SHORT).show();
        }
        Log.i(TAG,"onClick:r=" + r);
        //计算
          if(btn.getId()==R.id.btn3){
              show.setText(String.format("%.2f",r*dollarRate));
          }else if(btn.getId()==R.id.btn2){
              show.setText(String.format("%.2f",r*euroRate));
          }else {
              show.setText(String.format("%.2f",r*wonRate));
          }
    }
    public void openOne(View btn){
        openConfig();
    }


    public void openConfig(){
        Intent intent =new Intent(this,MainActivity2.class);

        intent .putExtra("dollar_rate_key",dollarRate);
        intent.putExtra("euro_rate_key",euroRate);
        intent.putExtra("won_rate_key",wonRate);

        Log.i(TAG,"openOne:  dollarRate" + dollarRate);
        Log.i(TAG,"openOne:  euroRate"  +  euroRate);
        Log.i(TAG,"openOne:   wonRate"  +   wonRate);

//        startActivity(intent );
         startActivityForResult(intent,1);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.rate,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.menu_set);

        SharedPreferences sharedPreferences= getSharedPreferences("myRate", Activity.MODE_PRIVATE);
        dollarRate = sharedPreferences.getFloat("dollar_rate",0.1f);
        euroRate = sharedPreferences.getFloat("euro_rate",0.1f);
        wonRate = sharedPreferences.getFloat("won_rate",0.1f);
        Log.d("Main1","get"+dollarRate);


        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if (requestCode == 1 && resultCode == 2){

            Bundle bundle = data.getExtras();
            dollarRate = bundle.getFloat("key_dollar",0.1f);
            euroRate = bundle.getFloat("key_euro",0.1f);
            wonRate = bundle.getFloat("key_won",0.1f);

            Log.i(TAG,"onActivityResult:  dollarRate" + dollarRate);
            Log.i(TAG,"onActivityResult:  euroRate" + euroRate);
            Log.i(TAG,"onActivityResult:  wonRate" + wonRate);

        }

        super.onActivityResult(requestCode, resultCode, data);
    }


    public  void  run(){
        Log.i(TAG,"run:  run .....");
        //睡眠三秒
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        //获取网络数据
//        URL url =null;
//        try{
//            url =new URL("https://huilv.911cha.com/");
//            HttpURLConnection http =(HttpURLConnection) url.openConnection();
//            InputStream in = http.getInputStream();
//            String html =inputStream2String(in);
//            Log.i(TAG,"run : html=" + html);
//            Document doc = Jsoup.parse(html);
//            String text = doc.body().text();
//
//
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
  //jsoup
        org.jsoup.nodes.Document doc = null;
        try {
            doc = Jsoup.connect("http://www.usd-cny.com/").get();
            Log.i(TAG,"run:  title="+  doc.title());
            Element firstTable = doc.getElementsByTag("table").first();
//            org.jsoup.nodes.Element firstTable=tables.first();
//            Log.i(TAG,"run:  table="+  firstTable);

            Elements trs =firstTable.getElementsByTag("tr");
            trs.remove(0);
            for (Element tr  :trs){
                //从行中获取td元素
                Elements tds =tr.getElementsByTag("td");
                Element td1 = tds.get(0);
                Element td2 = tds.get(4);
                Log.i(TAG,"run:td1="  + td1.text()+ "---->"  + td2.text());
                if ("美元".equals(td1.text())){
                    dollarRate=100/Float.parseFloat(td2.text());
                }
                if ("欧元".equals(td1.text())){
                    euroRate=100/Float.parseFloat(td2.text());
                }
                if ("韩币".equals(td1.text())){
                    wonRate=100/Float.parseFloat(td2.text());
                }
            }
            SharedPreferences sp = getSharedPreferences("myRate", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putFloat("dollar_rate",dollarRate);
            editor.putFloat("euro_rate",euroRate);
            editor.putFloat("won_rate",wonRate);
            editor.apply();


        } catch (IOException e) {
            e.printStackTrace();
        }

        //String text = doc.body().text();
        Message msg =handle.obtainMessage();
        msg.what=6;
        msg.obj ="  hello from run";
        handle.sendMessage(msg);
        Log.i(TAG,"run:消息已发送"); }
    @NonNull
    private  String inputStream2String(InputStream inputStream) throws IOException {
            final int bufferSize =1024;
            final char[] buffer =new char[bufferSize];
            final  StringBuilder out =new StringBuilder();
             Reader in =   new InputStreamReader(inputStream,"utf-8");
             while (true){
                 int rsz = in.read(buffer,0,buffer.length);
                 if (rsz<0)
                     break;;
                     out.append(buffer,  0, rsz);
             }
             return  out.toString();
         }
     }

